package com.lx.controller;

import com.lx.dao.NewsEsRepository;
import com.lx.entity.News;
import com.lx.service.NewsService;
import com.lx.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api")
@Api(tags = "新闻咨询管理接口")
public class NewsController{
    @Autowired
    NewsService newsService;
    @Autowired
    NewsEsRepository newsEsRepository;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping("/news/pageinfo")
    @ApiOperation(value = "分页查询新闻咨询列表",notes = "根据条件查询分页列表")
    public Result getPageInfo(@ApiParam(value = "查询参数", required = true)@RequestBody Map<String,Object> params){
        if(params.containsKey("title") &&
                (params.get("title") == null || params.get("title").toString().isEmpty())) {
            params.remove("title");
        }

        if(params.containsKey("createTime") &&
                (params.get("createTime") == null || params.get("createTime").toString().isEmpty())) {
            params.remove("createTime");
        }

        return Result.success(5200, "获取pageinfo成功").add("pageinfo", newsService.getPageInfo(params));
    }

    @PostMapping("/news/detail")
    @ApiOperation(value = "查询新闻详情", notes = "根据新闻ID查询新闻详情")
    public Result getNewsDetail(@ApiParam(value = "新闻ID参数", required = true)  @RequestBody Map<String, Object> params) {
        Object idObj = params.get("id");
        Integer id = null;

        // 直接处理字符串类型
        if (idObj instanceof String) {
            id = Integer.valueOf((String) idObj);
        } else if (idObj instanceof Integer) {
            id = (Integer) idObj;
        }

        if (id == null) {
            return Result.error().add("msg", "新闻ID不能为空");
        }

        News news = newsService.selectById(id);
        if (news != null) {
            return Result.success().add("list", news);
        } else {
            return Result.error().add("msg", "未找到指定的新闻");
        }
    }





    /**
     * 添加新闻
     */
    @PostMapping("/news/addnews")
    @ApiOperation(value = "添加新闻咨询", notes = "添加新的新闻咨询")
    public Result addNews(@ApiParam(value = "新闻信息参数", required = true) @RequestBody Map<String, Object> params) {
        // 从参数中提取新闻信息
        News news = new News();

        if (params.containsKey("title") && params.get("title") != null) {
            news.setTitle(params.get("title").toString());
        }

        if (params.containsKey("content") && params.get("content") != null) {
            news.setContent(params.get("content").toString());
        }

        boolean result = newsService.addNews(news);
        if (result) {
            //获取新增资讯的id，并加入es中
            news = newsService.getNewsByTitle(news.getTitle());
            newsEsRepository.save(news);
            return Result.success(5200, "添加新闻成功");
        } else {
            return Result.error(5500, "添加新闻失败");
        }
    }

    /**
     * 更新新闻
     */
    @PostMapping("/news/updatenews")
    @ApiOperation(value = "修改新闻咨询", notes = "修改咨询")
    public Result updateNews(@ApiParam(value = "新闻信息参数", required = true) @RequestBody Map<String, Object> params) {
        if (!params.containsKey("id") || params.get("id") == null) {
            return Result.error(5000, "后台校验错误");
        }
        News news =  newsService.selectById(Integer.parseInt(params.get("id").toString()));
        if (params.containsKey("title") && params.get("title") != null) {
            news.setTitle(params.get("title").toString());
        }

        if (params.containsKey("content") && params.get("content") != null) {
            news.setContent(params.get("content").toString());
        }

        boolean result = newsService.updateNews(news);
        if (result) {
            newsEsRepository.save(news); //修改es中数据，直接覆盖
            return Result.success(5200, "更新新闻成功");
        } else {
            return Result.error(5500, "更新新闻失败");
        }
    }

    /**
     * 删除新闻
     */
    @PostMapping("/news/delete")
    @ApiOperation(value = "删除新闻咨询", notes = "删除咨询")
    public Result deleteNews(@ApiParam(value = "新闻ID参数", required = true) @RequestBody Map<String, Object> params) {
        try {
            int id = Integer.parseInt(params.get("id").toString());
            boolean result = newsService.delNews(id);
            if (result) {
                //同时删除es中数据
                newsEsRepository.deleteById(String.valueOf(id));
                return Result.success(5200, "删除新闻成功");
            } else {
                return Result.error(5500, "删除新闻失败");
            }
        } catch (Exception e) {
            return Result.error(5500, "参数错误: " + e.getMessage());
        }
    }

}
